package job.work.utils;

import job.work.domain.common.JwtResponse;
import job.work.domain.system.entity.pojo.dto.AuthToken;
import job.work.domain.system.entity.pojo.model.SystemUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

/**
 * Created by echisan on 2018/6/23
 */
@Component
@Slf4j
public class JwtTokenUtils {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "jwtsecretdemo";
    private static final String ISS = "echisan";

    // 角色的key
    private static final String ROLE_CLAIMS = "rol";


    // 过期时间是3600秒，既是1个小时
    private static final long EXPIRATION = 36000L;//360000L

    // 选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 6048000L;//6048000L

    // 创建token
    public static String createToken(String username,String role, boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        HashMap<String, Object> map = new HashMap<>();
        map.put(ROLE_CLAIMS, role);

        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    // 从token中获取用户名
    public static String getUsername(String token){
        Claims tokenBody = getTokenBody(token);
        if (tokenBody!=null){
            return tokenBody.getSubject();
        }
        return null;

    }

    // 获取用户角色
    public static String getUserRole(String token){
        Claims tokenBody = getTokenBody(token);
        if ( tokenBody== null){
            return null;
        }
        return  (String) tokenBody.get(ROLE_CLAIMS);

    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        try {
            //log.info("输出token--->{}",token);
            Claims tokenBody = getTokenBody(token);

            if(tokenBody == null){
                return  false;
            }

            Date expiration = tokenBody.getExpiration();

            log.info("测试打印---expiration:{}",expiration);


            return expiration.before(new Date());

            // return getTokenBody(token).getExpiration().before(new Date());
        } catch (ExpiredJwtException e) {
            return false;
        }
    }


    private static Claims getTokenBody(String token){

        Claims body = null;
        try{
            body   = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        }
        catch (Exception e){
            return  null;
        }
        return body;
    }

    public static AuthToken createTokenUser(SystemUser systemUser){
        boolean isRemember = true;
        String token = JwtTokenUtils.createToken(systemUser.getUsername(), String.valueOf(systemUser.getRoleId()), isRemember);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        //把对象转化为String
        JwtResponse jwtResponse = new JwtResponse(JwtTokenUtils.TOKEN_PREFIX + token);
        String jwttoken = jwtResponse.getJwttoken();
        log.info("token--->:{}",token);
        AuthToken authToken = new AuthToken();
        authToken.setJwt_token(jwttoken);
        return authToken;
    }
}
